package com.tzt.controller.app;

import com.alibaba.fastjson.JSON;
import com.tzt.common.BaseController;
import com.tzt.dao.OrderMapper;
import com.tzt.entity.OrderEntity;
import com.tzt.service.AlipayService;
import com.tzt.util.NomalUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AlipayController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AlipayService alipayService;
    @Resource
    private OrderMapper orderMapper;
    @Value("${alipay.publickey}")
    public String publickey;
    @Value("${alipay.charset}")
    public String charset;
    @Value("${alipay.signtype}")
    public String signtype;

    @RequestMapping(value = "/api/getOrderInfoByAli", method = RequestMethod.POST)
    public String getOrderInfoByAli(String body, String subject, String outTradeNo, String timeoutExpress, String totalAmount) {
        if (NomalUtil.isNull(body) || NomalUtil.isNull(subject) || NomalUtil.isNull(outTradeNo) || NomalUtil.isNull(timeoutExpress) || NomalUtil.isNull(totalAmount)) {
            return JSON.toJSONString("parameter error");
        }
        return JSON.toJSONString(alipayService.getOrderInfoByAli(body, subject, outTradeNo, timeoutExpress, totalAmount));
    }

    /**
     * 遗留问题-验签未过
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/aliNotify", method = RequestMethod.POST)
    public Map<String, Object> aliNotify(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
//        logger.info("@@@@@@@@@@@@@@@@@" + JsonUtil.convertMapToJson(requestParams));
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            if (!"token".equals(name)) {
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            OrderEntity order = orderMapper.getOrderInfoByOrderId(params.get("out_trade_no"));
            if (params.get("out_trade_no").equals(order.getOrderNumber()) && order.getOrderAmount().compareTo(new BigDecimal(params.get("total_amount"))) == 0) {
//            if (AlipaySignature.rsaCheckV1(params, publickey, charset, signtype)) {
                OrderEntity orderEntity = new OrderEntity();
                orderEntity.setTradeNo(params.get("trade_no"));
                orderEntity.setStatus(0);
                orderEntity.setOrderNumber(params.get("out_trade_no"));
                orderEntity.setPaymentTime(new Date());
                orderEntity.setBuyerUserId(params.get("buyer_id"));
                orderEntity.setPayType("alipay");
                orderMapper.updatePayStatus(orderEntity);
                return successData(new HashMap<String, Object>());
            } else {
                return paramFailedMessage();
            }
        } catch (Exception e) {
//        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return paramFailedMessage();
        }
    }

}
